package com.openroom.ui;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.pivot.util.concurrent.TaskExecutionException;
import org.apache.pivot.wtk.ApplicationContext;
import org.apache.pivot.wtk.Label;
import org.apache.pivot.wtk.Meter;

import com.jphotomanager.io.ImageImporter;
import com.jphotomanager.io.RawConverter;
import com.openroom.db.DBHelper;
import com.openroom.model.Folder;
import com.openroom.model.ModelLocator;
import com.openroom.model.Photograph;

public class PreviewMakingTask extends ThumbnailMakingTask {

	public PreviewMakingTask(Meter meter, Label label, Folder folder) {
		super();
		this.meter = meter;
		this.label = label;
	}

	@Override
	public Void execute() throws TaskExecutionException {
		List<Photograph> list = ModelLocator.getInstance()
				.getAllPhotographsOfFolder();
		// Simulate a long-running operation
		percentage = ((double) fileCounter) / list.size();
		if (label != null)
			label.setText("Creating preview");
		else {
			System.out.println("Label is null");
		}
		if (meter != null)
			meter.setPercentage(0.0D);
		for (Photograph file : list) {
			try {
				if (abort)
					return null;
				fileCounter++;
				final Photograph file2 = file;
				File rawFile = new File(file2.getRawFilePath());
				if (ImageImporter.isRawFile(rawFile) && !RawConverter.isSupportedRawFile(rawFile)) {
					// Raw file preview still not supported
					continue;
				}
				BufferedImage read = ImageIO.read(rawFile);
				ImageImporter.createPreviewImageForViewedItems(file2, read);
				// Update the meter on the UI thread
				ApplicationContext.queueCallback(new Runnable() {
					@Override
					public void run() {
						if (meter != null && meter.isVisible()) {
							meter.setPercentage((double) percentage);
							label.setText("Creating preview for "
									+ file2.getFileName());
						}
					}
				});
				percentage = ((double) fileCounter) / list.size();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		DBHelper.getInstance().commit();
		return null;
	}
}
